package com.demo.sonar;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.Base64;

public class SonarData {


    private static final String SONAR_URL = "http://10.252.171.40:30003"; // SonarQube 服务器地址
    private static final String AUTH_TOKEN = "c1a055b63b775f093c69ea4db7cc9ee49fda72b9"; // 认证信息，可能是令牌或Base64编码的用户名:密码

    public static void main(String[] args) {

        String url = "http://10.252.171.40:30003/api/projects/search";
        HttpGet request = new HttpGet(url);
        request.setHeader("Authorization", "Basic " + Base64.getEncoder().encodeToString("admin:123456".getBytes())); // 使用Base64编码的用户名和密码
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try (CloseableHttpResponse response = httpClient.execute(request)) {
            HttpEntity entity = response.getEntity();
            System.out.println("相应数据=======");
            System.out.println(JSONObject.toJSONString(entity));
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
       /* String projectKey = "your_project_key";
        String[] metricKeys = {"ncloc", "violations", "coverage"};

        try {
            String jsonResponse = getMetrics(projectKey, metricKeys);
            System.out.println(jsonResponse);

            // 这里可以添加代码来解析JSON响应
            JSONObject jsonObject = JSONObject.parseObject(jsonResponse);
//            JSONObject jsonObject = new JSONObject(jsonResponse);
            // ... 进一步处理JSON数据

        } catch (IOException e) {
            e.printStackTrace();
        }*/
    }

    private static String getMetrics(String projectKey, String[] metricKeys) throws IOException {
        String url = SONAR_URL + "/api/measures/component?component=" + projectKey + "&metricKeys=" + String.join(",", metricKeys);

        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet request = new HttpGet(url);
        request.setHeader("Authorization", "Basic " + AUTH_TOKEN); // 如果使用基本认证
        // 或者如果是令牌认证，可能需要不同的头部，如 "Authorization: Bearer " + AUTH_TOKEN

        try (CloseableHttpResponse response = httpClient.execute(request)) {
            HttpEntity entity = response.getEntity();
            return entity != null ? EntityUtils.toString(entity, "UTF-8") : null;
        }
    }

}
